//
//  WelcomeViewController.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/12.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
class WelcomeViewController: UIViewController {

    var backView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    var headView: UIImageView = UIImageView()
    var welcomeLabel: UILabel = {
        let label = UILabel()
        label.text = (UserAccountViewModel().account?.name ?? "") + " 欢迎归来"
        label.textColor = UIColor.lightGrayColor()
        label.textAlignment = NSTextAlignment.Center
        label.font = UIFont.systemFontOfSize(18)
        label.alpha = 0
//        label.sizeToFit()
        return label
    }()

    override func loadView() {
        view = backView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    func setupUI() {
        //添加子视图
        view.addSubview(headView)
        view.addSubview(welcomeLabel)
        //设置headView
        headView.sd_setImageWithURL(UserAccountViewModel().headIconUrl, placeholderImage: UIImage(named: "ad_background"))
        //设置头像为圆形
        headView.layer.cornerRadius = 45
        headView.clipsToBounds = true
        //设置布局
        headView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-180)
            make.width.equalTo(90)
            make.height.equalTo(90)
        }
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.top.equalTo(headView.snp_bottom).offset(20)
        }
    }
    
    //不要再viewDidLoad中去做动画
    override func viewDidAppear(animated: Bool) {
        startAnimation()
    }
    
    private func startAnimation() {
        headView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(200 - kScreenSize.height)
        }
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 9, options: [], animations: { () -> Void in
                    self.view.layoutIfNeeded()
            }) { (_) -> Void in
                UIView.animateWithDuration(0.6, animations: { () -> Void in
                    self.welcomeLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        print("welcomeLabel动画结束")
                NSNotificationCenter.defaultCenter().postNotificationName(appSwitchRootViewcontroller, object: nil)
                })
        }
    }
    
    
}
